package com.javaweb.dao.impl;

import com.javaweb.dao.CommentDao;
import com.javaweb.model.Comment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Repository
@Slf4j
public class CommentDaoImpl implements CommentDao {

    @Autowired
    JdbcTemplate jdbcTemplate ;

    @Override
    public int insert(Comment newComment) {
        String sql = "INSERT INTO tb_comment (content, article_id, user_id, support, " +
                "oppose, create_time, update_time)" +
                " VALUES (?,?,?,?,?,?,?)" ;

        if(newComment.getArticleId() == null || newComment.getArticleId() == 0){
            return 0;
        }

        Object[] args = new Object[]{
                newComment.getContent(),
                newComment.getArticleId(),
                newComment.getUserId(),
                newComment.getSupport(),
                newComment.getOppose(),
                new java.sql.Date(new Date().getTime()),
                new java.sql.Date(new Date().getTime())
        };

        return jdbcTemplate.update(sql,args);
    }

    @Override
    public int insertSupport(Integer commentId) {
        String sql = "UPDATE tb_comment set support = support + 1 where id = ?" ;

        Object[] args = new Object[]{
                commentId
        };

        return jdbcTemplate.update(sql,args);
    }

    @Override
    public int insertOppose(Integer commentId) {
        String sql = "UPDATE tb_comment set oppose = oppose + 1 where id = ?" ;

        Object[] args = new Object[]{
                commentId
        };

        return jdbcTemplate.update(sql,args);
    }

    @Override
    public List<Comment> selectAllCommentsById(Integer articleId) {
        String sql = "select * from tb_comment where article_id = ?";

        return jdbcTemplate.query(sql,new Object[]{articleId},
                rs -> {
                    List<Comment> list = new ArrayList<>();
                    while (rs.next()){
                        Comment comment = new Comment();
                        comment.setId(rs.getInt("id"));
                        comment.setUserId(rs.getInt("user_id"));
                        comment.setArticleId(rs.getInt("article_id"));
                        comment.setContent(rs.getString("content"));
                        comment.setSupport(rs.getInt("support"));
                        comment.setOppose(rs.getInt("oppose"));
                        list.add(comment);
                    }
                    return list;
                });

    }


}
